/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/17
 * Time:11:27
 **/
public class Main2 {
    /**
     * 每日一题-把字符串转换成整数
     *
     * @param str
     * @return
     */
    public int StrToInt(String str) {
        if (str == null || str.equals("")) {
            return 0;
        }
        int result = 0;
        boolean negative = false;
        int i = 0;
        int len = str.length();
        int limit = -Integer.MAX_VALUE;//最大正数
        int multmin = 0;
        int digit = 0;
        if (len > 0) {
            char first = str.charAt(0);
            if (first < '0') {
                if (first == '-') {//为负
                    negative = true;
                    limit = Integer.MIN_VALUE;//最小负数
                } else if (first != '+') {
                    return 0;//说明不合法
                }
                if (len == 1) {
                    return 0;
                }
                i++;
            }
            multmin = limit / 10;
            while (i < len) {
                digit = str.charAt(i++) - '0';//char 转换为 int
                //<0 >9的数字
                if (digit < 0 || digit > 9) {
                    return 0;
                }
                //溢出
                if (result < multmin) {
                    return 0;
                }
                result *= 10;
                if (result < limit + digit) {
                    return 0;
                }
                result -= digit;
            }
        } else {
            return 0;
        }
        //若为正数返回:-result
        return negative ? result : -result;
    }

    public int StrToInt2(String str) {
        char[] chs = str.toCharArray();
        if (chs == null || chs.length == 0) {
            return 0;
        }
        int flg = 1;
        if (chs[0] == '-') {
            flg = -1;
            chs[0] = '0';
        } else if (chs[0] == '+') {
            flg = 1;
            chs[0] = '0';
        }
        int sum = 0;
        for (int i = 0; i < str.length(); i++) {
            if (chs[i] > '9' && chs[i] < '0') {
                sum = 0;
                break;
            }
            sum = sum * 10 + chs[i] - '0';
        }
        return flg * sum;//返回int类型
    }
}

